<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" placeholder="输入内容">
  <button>发送请求</button>
  <!--接收消息-->
  <div></div>
  <script>     
      var input = document.querySelector('input');
      var button = document.querySelector('button');
      var div = document.querySelector('div');
      const TYPE_ENTER = 0
      const TYPE_LEAVE = 1
      const TYPE_MSG = 2
       //创建websocket对象
      var socket = new WebSocket('ws://localhost:3003');
      socket.addEventListener('open',function(){
          div.innerHTML = '连接服务器成功'

      })
      //主动给websocket服务发送消息
      button.addEventListener('click',function(){
          var value = input.value
          socket.send(value)
          input.value = ''
      })
      socket.addEventListener('message',function(e){
          var data = JSON.parse(e.data)
          var dv = document.createElement('div')
          dv.innerText = data.msg +'------'+data.time
          if(data.type === TYPE_ENTER){
              dv.style.color = 'green'
          }else if(data.type === TYPE_LEAVE){
              dv.style.color = 'red'
          }else{
              dv.style.color = 'blue'
          }
          div.appendChild(dv)
      })
      socket.addEventListener('close',function(){
          div.innerHTML = '服务断开链接'
      })
  </script>
  
</body>
</html>